package com.credit.mola.app.ui.permission

import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.credit.mola.app.R
import com.credit.mola.app.adapter.PermissionReasonAdapter
import com.credit.mola.app.databinding.ActivityPermissionReasonBinding
import com.credit.mola.app.pro.ProActivity
import com.credit.mola.app.utils.BarUtils
import com.credit.mola.app.utils.DensityUtils
import com.credit.mola.app.utils.config.Configs
import com.credit.mola.app.utils.dialog.TipsDialog
import com.credit.mola.app.utils.event.EventType
import com.credit.mola.app.utils.rv.LinearDecoration
import com.credit.mola.lib_permission.OnPermissionCallback
import com.credit.mola.lib_permission.Permission
import com.credit.mola.lib_permission.XXPermissions
import org.json.JSONObject
import java.math.BigDecimal

/**
 * 权限说明列表
 */
class PermissionReasonActivity : ProActivity() {
    private val INTENT_KEY_AMOUNT = "amount"
    lateinit var binding: ActivityPermissionReasonBinding
    private var itemAdapter: PermissionReasonAdapter? = null

    override fun getRootView(): View {
        binding = ActivityPermissionReasonBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        binding.permissionContentLayout.setPadding(0, BarUtils.getStatusBarHeight(),0,0)
        initPermissionListView()
    }

    override fun initListener() {
        //返回
        binding.imgBack.setOnClickListener {
            finish()
        }
        //客服
        binding.imgKefu.setOnClickListener {
            showKefuDialog("Permission Page")
            addEvent(EventType.CLICK.CLICK_CUSTOMER,"Permission Page")
        }

//        binding.checkBox.setOnCheckedChangeListener { _, isChecked ->
//            when (isChecked) {
//                true -> {
//                    binding.btnPermissionAgree.isEnabled = true
//                }
//                false -> {
//                    binding.btnPermissionAgree.isEnabled = false
//                }
//            }
//        }

        //拒绝
        binding.btnPermissionDeny.setOnClickListener {
            Configs.saveSPInt(Configs.SPKEY.SIKADWA_PERMISSION_REASON_STATUS,-1)
            addEvent(EventType.CLICK.CLICK_PERMISSION_DENY,"Permission Page")

            val intent = intent
            intent.putExtra("isPermissionAgree",false)
            setResult(RESULT_OK,intent)
            finish()
        }

        //同意权限
        binding.btnPermissionAgree.setOnClickListener {
            addEvent(EventType.CLICK.CLICK_PERMISSION_AGREE,"Permission Page")
            if (!binding.checkBox.isChecked){
                showPermissionAgreedDialog()
                return@setOnClickListener
            }
            Configs.saveSPInt(Configs.SPKEY.SIKADWA_PERMISSION_REASON_STATUS,1)
            loadSikadwaPermissionAction()
        }
    }

    override fun initData() {
        val showAmount = getLimitAmount()
        val itemList = arrayListOf<JSONObject>()
        val mesagItem = PermHelper.getCreditMolaMESAGItem()
        mesagItem.put("passRate","30")
        mesagItem.put("loanAmount", BigDecimal(showAmount).multiply(BigDecimal("0.15")).stripTrailingZeros().toPlainString())
        itemList.add(mesagItem)

        val deviceItem = PermHelper.getCreditMolaPhoneStateItem()
        deviceItem.put("passRate","10")
        deviceItem.put("loanAmount", BigDecimal(showAmount).multiply(BigDecimal("0.05")).stripTrailingZeros().toPlainString())
        itemList.add(deviceItem)

        val apListItem = PermHelper.getCreditMolaAPListItem()
        apListItem.put("passRate","10")
        apListItem.put("loanAmount", BigDecimal(showAmount).multiply(BigDecimal("0.05")).stripTrailingZeros().toPlainString())
        itemList.add(apListItem)

        val cameraItem = PermHelper.getCreditMolaCameraItem()
        cameraItem.put("passRate","10")
        cameraItem.put("loanAmount", BigDecimal(showAmount).multiply(BigDecimal("0.05")).stripTrailingZeros().toPlainString())
        itemList.add(cameraItem)

        val storageItem = PermHelper.getCreditMolaStorageItem()
        storageItem.put("passRate","10")
        storageItem.put("loanAmount", BigDecimal(showAmount).multiply(BigDecimal("0.05")).stripTrailingZeros().toPlainString())
        itemList.add(storageItem)

        val phoneBookItem = PermHelper.getCreditMolaPhoneBookItem()
        phoneBookItem.put("passRate","10")
        phoneBookItem.put("loanAmount", BigDecimal(showAmount).multiply(BigDecimal("0.05")).stripTrailingZeros().toPlainString())
        itemList.add(phoneBookItem)

        val albumItem = PermHelper.getCreditMolaPhotoAlbumItem()
        albumItem.put("passRate","10")
        albumItem.put("loanAmount", BigDecimal(showAmount).multiply(BigDecimal("0.05")).stripTrailingZeros().toPlainString())
        itemList.add(albumItem)

        itemAdapter?.data = itemList
    }

    /**
     * 初始化权限列表
     */
    private fun initPermissionListView(){
        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val topDecoration = DensityUtils.dp2px(10f)
        binding.recyclerView.addItemDecoration(LinearDecoration(0,0,topDecoration,topDecoration))
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        itemAdapter = PermissionReasonAdapter(binding.recyclerView)
        binding.recyclerView.adapter = itemAdapter
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
    }

    /**
     * 获取额度
     */
    private fun getLimitAmount(): String{
        intent.extras?.let {
            return it.getString(INTENT_KEY_AMOUNT,"0").toString()
        }
        return "0"
    }

    /**
     * 阅读与同意
     */
    private fun showPermissionAgreedDialog(){
        val tipsDialog = TipsDialog(this,"Permission Page",object : TipsDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view?.id == R.id.btnOk){
                    binding.checkBox.isChecked = true
                    binding.btnPermissionAgree.callOnClick()
                }
            }
        })
        tipsDialog.setCancelable(true)
        tipsDialog.setCanceledOnTouchOutside(false)
        tipsDialog.show()
        tipsDialog.setTipsTitle(getString(R.string.tips_kind))
        tipsDialog.setTips(getString(R.string.permission_agree_tips))
    }

    /**
     * 申请权限
     */
    private fun loadSikadwaPermissionAction(){
        XXPermissions.with(this)
            .permission(Permission.READ_SMS)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        addEvent(EventType.CLICK.CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))

                        val intent = intent
                        intent.putExtra("isPermissionAgree",true)
                        setResult(RESULT_OK,intent)
                        finish()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    permissions.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    addEvent(EventType.CLICK.CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))
                    XXPermissions.startPermissionActivity(this@PermissionReasonActivity,Permission.READ_SMS)
                }
            })
    }

    override fun onStart() {
        super.onStart()
        addEvent(EventType.PAGE.PAGE_PERMISSION_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_PERMISSION_END)
    }
}